<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\traits\MyModelTrait;
use think\facade\Session;

/**
 * @mixin \think\Model
 */
class AdminRolePermission extends Model
{
    use MyModelTrait;

    // 角色绑定权限表
    protected $table = "admin_role_permission";

    /**
     * 生成日志
     *
     * @param int $admin_role_id
     * @param int $admin_permission_id
     * @return void
     */
    public static function generateLog(int $admin_role_id, int $admin_permission_id): void
    {
        $insert = [
            'admin_role_id'         => $admin_role_id,
            'admin_permission_id'   => $admin_permission_id
        ];
        self::insert($insert);
    }// generateLog() end

    /**
     * 获取所有权限 ID
     *
     * @param int $admin_role_id
     * @return array
     */
    public static function getPermissionIds(int $admin_role_id): array
    {
        return self::where('admin_role_id', $admin_role_id)->column('admin_permission_id');
    }// getPermissionIds() end

    /**
     * 处理角色权限数据，主要处理是否有已选中的选项
     *
     * @param int   $admin_role_id  admin_user.admin_role_id
     * @param array $data           从 app\model\AdminPermission::getPermission() 获取的数据
     * @return array
     */
    public static function handleChecked(int $admin_role_id, array $data): array
    {
        $ids = self::getPermissionIds($admin_role_id);
        if (empty($ids)) return $data;
        foreach($data as $index => $permission){
            //dump($permission);
            /*array:6 [
                "id"        => 1
                "title"     => "系统设置"
                "field"     => "title"
                "checked"   => false
                "spread"    => false
                "children"  => array:87 [
                    0 => array:6 [
                        "id"        => 7
                        "title"     => "菜单(admin/menu/index)"
                        "uri"       => "admin/menu/index"
                        "pid"       => 1
                        "field"     => "title"
                        "checked"   => false
                    ]
                ]
            ]*/

            $data[$index]['spread'] = false;// true-展开，false-折叠
            foreach($permission['children'] as $index2 => $child){
                //dump($child);
                /*array:6 [
                    "id"        => 7
                    "title"     => "菜单(admin/menu/index)"
                    "uri"       => "admin/menu/index"
                    "pid"       => 1
                    "field"     => "title"
                    "checked"   => false
                ]*/
                if (in_array($child['id'], $ids)) $data[$index]['children'][$index2]['checked'] = true;// 勾选
            }
        }
        return $data;
    }// handleChecked() end

    /**
     * 设置角色权限 ID
     *
     * @param int $admin_role_id    admin_user.admin_role_id
     * @return void
     */
    public static function setPermissionIdsForSession(int $admin_role_id): void
    {
        $permission_ids = self::getPermissionIds($admin_role_id);
        Session::set('admin_user.permission_ids', $permission_ids);
    }// setPermissionIdsForSession() end

    /**
     * 判断角色权限 id 是否有访问权限
     *
     * @param int    $admin_role_id     admin_user.admin_role_id
     * @param string $uri               admin_permission.uri
     * @return bool true-是
     */
    public static function isPass(int $admin_role_id, string $uri): bool
    {
        $permission = AdminPermission::whereRaw("uri = :uri", ['uri' => $uri])->findOrEmpty();
        if ($permission->isEmpty()) return false;
        if (in_array((int)$permission->id, Session::get('admin_user.permission_ids', []))) return true;
        return false;
    }// isPass() end

    /**
     * 设置角色权限缓存数据
     * @param array $role_permission 从 self::handleChecked() 获得的数据
     * @return void
     */
    public static function setRolePermissionToCache(array $role_permission): void
    {
        $key   = 'admin_role_id_list';
        $redis = MyRedis::getRedisInstance();
        $json  = str_replace('\\/', '/', json_encode($role_permission, JSON_UNESCAPED_UNICODE));
        $redis->set($key, $json);
    }// setRolePermissionToCache() end

    /**
     * 获取角色缓存数据
     *
     * @param int $admin_role_id    admin_role.id
     * @return array
     */
    public static function getRolePermissionFromCache(int $admin_role_id): array
    {
        $key   = 'admin_role_id_list';
        $redis = MyRedis::getRedisInstance();
        $permission = AdminPermission::getPermission();
        if(1 > $redis->exists($key)) self::setRolePermissionToCache($permission);
        $json = $redis->get($key);
        return AdminRolePermission::handleChecked($admin_role_id, json_decode($json, true));
    }// getRolePermissionFromCache() end
}
